<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>34、受控组件</title>
</head>
<body>
  <div id="test"></div>

  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://cdn.staticfile.org/prop-types/15.6.1/prop-types.js"></script>

  <script type="text/babel">
    // 比起非受控组件，推荐使用受控组件
    // 创建组件
    class Login extends React.Component{
      // 初始化状态
      state = {
        username: '',
        password: '',
      }

      saveUsername = (event) => {
        // 将数据存储在状态中
        this.setState({
          username: event.target.value,
        })
      }

      savePassword = (event) => {
        // 将数据存储在状态中
        this.setState({
          password: event.target.value,
        })
      }

      handleSubmit = (event) => {
        event.preventDefault()  // 组织表单提交
        const {username, password} = this.state   
        alert(`用户名：${username}，密码：${password}`)
      }
      // 页面中所有输入类dom，例如checkbox、input等，现用现取，就是非受控组件
      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            用户名：<input onChange={this.saveUsername} type="text" name="username"/> 
            密码：<input onChange={this.savePassword} type="password" name="password"/> 
            <button>登录</button>
          </form>
        )
      }
    }
    // 渲染组件到页面
    ReactDOM.render(<Login />, document.getElementById('test'))
  </script>
</body>
</html>